#!/bin/bash

# Variables from Ansible playbook
target_network="{{ target_network }}"
gateway="{{ gateway }}"
interface="{{ interface }}"

# Check if the route already exists
route_exists=$(ip route show | grep -E "^[0-9]+(\.[0-9]+){3}\s+via\s+{{ gateway }}\s+dev\s+{{ interface }}$")

# If the route does not exist, add it
if [ -z "$route_exists" ]; then
  ip route add $target_network via $gateway dev $interface
  if [ $? -eq 0 ]; then
    echo "Route added successfully: $target_network via $gateway dev $interface"
  else
    echo "Failed to add route: $target_network via $gateway dev $interface"
    exit 1
  fi
else
  echo "Route already exists: $target_network via $gateway dev $interface"
fi
